# File:	    5_TableA3b-withC
# Project:	Colonial legacy and foreign aid: Decomposing the colonial bias
# Authors:	Daina Chiba, Department of Government, University of Essex
#           Tobias Heinrich, Department of Political Science, University of South Carolina
# Contact:	dchiba@essex.ac.uk
# Date:     20 November, 2018

# Description: 
# This R script file replicates the results reported in Table A.3 and Figure A.3
# in Appendix D and E (with controls). 

# Preparation -------------------------------------------------------------
rm(list=ls())
library(foreign)
library(MCMCglmm)
library(texreg)

# Define auxiliary functions
source("aux_functions.R")


# Data manipulation -------------------------------------------------------
fa.data <- read.dta("colony-dummy.dta")

## log(0)
fa.data $ tobitDV <- fa.data $ lnGrossAid - log(.001)
fa.data $ tobitDV[fa.data $ AnyGrossAid == 0] <- 0

names(fa.data)

## Listwise delete missing values
fa.data.nna <- fa.data[, c("tobitDV", "RA", "RB", "WBdum2", "WBdum3", "WBdum4","WBdum5", "WB",
                           "Ltrade", "Ltau_glob", "Ltau2", "colony", "lnMultiAid", "rgdpchB", "LkgB",
                           "lnDIS", "ColdWar", "lnPOPB", "dyad", "year", "rCNAME","dCNAME")]
fa.data.nna <- na.omit(fa.data.nna)
fa.data.nna $ RB2 <- fa.data.nna $ RB^2
fa.data.nna $ LkgB2 <- fa.data.nna $ LkgB^2
fa.data.nna $ wealthB <- log(fa.data.nna $ rgdpchB)
fa.data.nna $ wealthB2 <- fa.data.nna $ wealthB^2
fa.data.nna $ lnPOPB2 <- fa.data.nna $ lnPOPB^2

## time variables
fa.data.nna $ yearid <- fa.data.nna $ year - 1959
fa.data.nna $ yearid2 <- fa.data.nna $ yearid^2
fa.data.nna $ yearid3 <- fa.data.nna $ yearid^3
fa.data.nna $ time <- (fa.data.nna $ year - mean(fa.data.nna $ year))/sd(fa.data.nna $ year)
fa.data.nna $ time2 <- (fa.data.nna $ time)^2
fa.data.nna $ time3 <- (fa.data.nna $ time)^3

## donor
length(unique(fa.data.nna $ dCNAME))
fa.data.nna $ donor <- as.numeric(as.factor(fa.data.nna $ dCNAME))

## recipient
length(unique(fa.data.nna $ rCNAME))
fa.data.nna $ recip <- as.numeric(as.factor(fa.data.nna $ rCNAME))

## Censoring
fa.data.nna $ YLow <- ifelse(fa.data.nna $ tobitDV == 0, -Inf, fa.data.nna $ tobitDV)

fa.data.nna.1 <- fa.data.nna[fa.data.nna $ colony == 1, ]
fa.data.nna.0 <- fa.data.nna[fa.data.nna $ colony == 0, ]

dim(fa.data.nna)

# Tobit models ------------------------------------------------------------

## Pooled (15 mins)
set.seed(123456789)
full2.p <- MCMCglmm(
  fixed = cbind(YLow, tobitDV) ~ RA + WBdum2 + WBdum3 + WBdum4 + WBdum5 + 
    wealthB + wealthB2 + lnPOPB + lnPOPB2 + LkgB + LkgB2 + 
    ColdWar + lnDIS + lnMultiAid + Ltrade + Ltau_glob + Ltau2 + time + time2 + time3 + 
    colony,
  random = ~us(1):dCNAME + us(1):rCNAME, 
  data = fa.data.nna,
  nitt = 11000,
  burnin = 1000,
  prior=list(R = list(V=1, nu=.001), G = list(G1=list(V=1, nu=.001), G2 = list(V=1, nu=.001))),
  family="cengaussian",
  thin = 10)

## Colony == 1 (30 sec)
set.seed(123456789)
full2.1 <- MCMCglmm(
  fixed = cbind(YLow, tobitDV) ~ RA + WBdum2 + WBdum3 + WBdum4 + WBdum5 + 
    wealthB + wealthB2 + lnPOPB + lnPOPB2 + LkgB + LkgB2 + 
    ColdWar + lnDIS + lnMultiAid + Ltrade + Ltau_glob + Ltau2 + time + time2 + time3,
    random = ~us(1):dCNAME + us(1):rCNAME, 
  data = fa.data.nna.1,
  nitt = 11000,
  burnin = 1000,
  prior=list(R = list(V=1, nu=.001), G = list(G1=list(V=1, nu=.001), G2 = list(V=1, nu=.001))),
  family="cengaussian",
  thin = 10)

## Colony == 0 (14 min)
set.seed(123456789)
full2.0 <- MCMCglmm(
  fixed = cbind(YLow, tobitDV) ~ RA + WBdum2 + WBdum3 + WBdum4 + WBdum5 + 
    wealthB + wealthB2 + lnPOPB + lnPOPB2 + LkgB + LkgB2 + 
    ColdWar + lnDIS + lnMultiAid + Ltrade + Ltau_glob + Ltau2 + time + time2 + time3,
  random = ~us(1):dCNAME + us(1):rCNAME, 
  data = fa.data.nna.0,
  nitt = 11000,
  burnin = 1000,
  prior=list(R = list(V=1, nu=.001), G = list(G1=list(V=1, nu=.001), G2 = list(V=1, nu=.001))),
  family="cengaussian",
  thin = 10)


save(full2.p, file = "output/mcmc/mcmc-full2-p.rda")
save(full2.1, file = "output/mcmc/mcmc-full2-1.rda")
save(full2.0, file = "output/mcmc/mcmc-full2-0.rda")

# Decomposition analyses --------------------------------------------------

# Calculate aggregate observables

(out <- calculate.qoi(fa.data.nna, group.var = "colony", 
                      fit.0 = full2.0, fit.1 = full2.1))

## decomposition based on E(Y)
(total.diff.3 <- out $ ey.x1.b1 - out $ ey.x0.b0)
(obs.contrib.3 <- out $ ey.x1.b0 - out $ ey.x0.b0)
obs.contrib.3 / total.diff.3

## decomposition based on pr(y>0)
(total.diff.1 <- out $ pry.x1.b1 - out $ pry.x0.b0)
(obs.contrib.1 <- out $ pry.x1.b0 - out $ pry.x0.b0)
obs.contrib.1 / total.diff.1

## decomposition based on E(Y | Y > 0)
(total.diff.2 <- out $ cy.x1.b1 - out $ cy.x0.b0)
(obs.contrib.2 <- out $ cy.x1.b0 - out $ cy.x0.b0)
obs.contrib.2 / total.diff.2

# Posterior distribution of these QoIs
nsim <- nrow(full2.0[[1]])
pb <- txtProgressBar()

# combine results from 3 chains
beta.3c.1 <- full2.1[[1]]
beta.3c.0 <- full2.0[[1]]
qoi.list <- c()

for ( i in 1:nsim) {
  beta.0 <- beta.3c.0[ i, ]
  beta.1 <- beta.3c.1[ i, ]  
  qoi.list <- rbind(qoi.list, 
                    as.data.frame(
                      calculate.qoi.full(fa.data.nna, 
                                         group.var = "colony", 
                                         fit.0 = full2.0, fit.1 = full2.1, 
                                         beta.0 = beta.0, beta.1 = beta.1)))
  setTxtProgressBar(pb,i/nsim)
}

# Plot QoIs ---------------------------------------------------------------

# E(Y)
obs.diff <- qoi.list $ ey.x1.b0 - qoi.list $ ey.x0.b0
tot.diff <- qoi.list $ ey.x1.b1 - qoi.list $ ey.x0.b0
ey.obs.pct <- 100 * obs.diff/tot.diff

# Pr(Y>0)
obs.diff <- qoi.list $ pry.x1.b0 - qoi.list $ pry.x0.b0
tot.diff <- qoi.list $ pry.x1.b1 - qoi.list $ pry.x0.b0
pry.obs.pct <- 100 * obs.diff/tot.diff

# E (y | y > 0)
obs.diff <- qoi.list $ cy.x1.b0 - qoi.list $ cy.x0.b0
tot.diff <- qoi.list $ cy.x1.b1 - qoi.list $ cy.x0.b0
cy.obs.pct <- 100 * obs.diff/tot.diff

quantile(ey.obs.pct, probs = c(.05, .5, .95))
quantile(pry.obs.pct, probs = c(.05, .5, .95))
quantile(cy.obs.pct, probs = c(.05, .5, .95))

# > quantile(ey.obs.pct, probs = c(.05, .5, .95))
# 5%      50%      95% 
# 12.71916 21.94706 49.66986 
# > quantile(pry.obs.pct, probs = c(.05, .5, .95))
# 5%      50%      95% 
# 23.83739 31.21919 50.38061 
# > quantile(cy.obs.pct, probs = c(.05, .5, .95))
# 5%      50%      95% 
# 11.42150 21.91345 56.62415 

pdf(file="output/figures/FigureA3_spec2_controls.pdf", width=5.5, height=4)
par(mar=c(2,6,2,3))
plot(0,0, type="n", xlim = c(0, 100), ylim = c(0.75,9.5), axes=F,ann=F)
### shades
shadeColor <- c("gray80", "gray92")
## E(Y )
polygon(y = c(7,7,9,9), x = c(0, 
                              quantile(ey.obs.pct, probs = c(.5)), 
                              quantile(ey.obs.pct, probs = c(.5)), 
                              0), col= shadeColor[1], border=F)
polygon(y = c(7,7,9,9), x = c(quantile(ey.obs.pct, probs = c(.5)), 
                              100, 100, 
                              quantile(ey.obs.pct, probs = c(.5))), 
        col= shadeColor[2], border=F)
lines(x = quantile(ey.obs.pct, probs = c(.05, .95)), y = c(8,8))
lines(x = quantile(ey.obs.pct, probs = c(.05, .05)), y = c(7.75, 8.25))
lines(x = quantile(ey.obs.pct, probs = c(.95, .95)), y = c(7.75, 8.25))
points(x = quantile(ey.obs.pct, probs = .5), y = 8, pch = 19)

## Pr(Y>0)
polygon(y = c(4,4,6,6), x = c(0, quantile(pry.obs.pct, probs = .5), quantile(pry.obs.pct, probs = .5)
                              , 0), col= shadeColor[1], border=F)
polygon(y = c(4,4,6,6), x = c(quantile(pry.obs.pct, probs = .5), 
                              100, 100, quantile(pry.obs.pct, probs = .5)), col= shadeColor[2], border=F)
lines(x = quantile(pry.obs.pct, probs = c(.05, .95)), y = c(5,5))
lines(x = quantile(pry.obs.pct, probs = c(.05, .05)), y = c(4.75, 5.25))
lines(x = quantile(pry.obs.pct, probs = c(.95, .95)), y = c(4.75, 5.25))
points(x = quantile(pry.obs.pct, probs = .5), y = 5, pch = 19)

## E(Y | Y>0)
polygon(y = c(1,1,3,3), x = c(0, quantile(cy.obs.pct, probs = .5),
                              quantile(cy.obs.pct, probs = .5), 0), col= shadeColor[1], border=F)
polygon(y = c(1,1,3,3), x = c(quantile(cy.obs.pct, probs = .5), 
                              100, 100, quantile(cy.obs.pct, probs = .5)), col= shadeColor[2], border=F)
lines(x = quantile(cy.obs.pct, probs = c(.05, .95)), y = c(2,2))
lines(x = quantile(cy.obs.pct, probs = c(.05, .05)), y = c(1.75, 2.25))
lines(x = quantile(cy.obs.pct, probs = c(.95, .95)), y = c(1.75, 2.25))
points(x = quantile(cy.obs.pct, probs = .5), y = 2, pch = 19)

xlabd <- c("0 %", "25 %","50 %","75 %","100 %")
axis(1, cex.axis=1, mgp=c(3,.4,0), labels=xlabd,at=c(0, 25, 50, 75, 100))
axis(2, labels = c("E(Y | Y > 0)", "Pr(Y > 0)", "E(Y)"), at=c(2, 5, 8), las = 1, tick = F)
text(9.5, 9.5, "Observables")
text(50, 9.5, "Saliency")
dev.off()


# Produce Table A.3 -------------------------------------------------------

# Load estimates for the left-hand side of the table
load("output/mcmc/mcmc-spec2-p.rda")
load("output/mcmc/mcmc-spec2-1.rda")
load("output/mcmc/mcmc-spec2-0.rda")

cf.names2 <- c("Intercept", "Donor Resource", 
               "W == 0.25", "W == 0.50", "W == 0.75", "W == 1", 
               "Recipient Wealth", "Recipient Wealth^2",
               "Recipient Population", "Recipient Population^2", 
               "Recipient Government Share", "Recipient Government Share^2", 
               "Cold War", "Distance", "Multilateral Aid", 
               "Trade", "Alignment", "Alignment^2",
               "time","time2","time3")
cf.names2.p <- c("Intercept", "Donor Resource", 
                 "W == 0.25", "W == 0.50", "W == 0.75", "W == 1", 
                 "Recipient Wealth", "Recipient Wealth^2",
                 "Recipient Population", "Recipient Population^2", 
                 "Recipient Government Share", "Recipient Government Share^2", 
                 "Cold War", "Distance", "Multilateral Aid", 
                 "Trade", "Alignment", "Alignment^2",
                 "time","time2","time3", "Colony")
cf.names2.nc <- c("Intercept", "Donor Resource", 
                  "W == 0.25", "W == 0.50", "W == 0.75", "W == 1", 
                  "Recipient Wealth", "Recipient Wealth^2",
                  "Recipient Population", "Recipient Population^2", 
                  "Recipient Government Share", "Recipient Government Share^2", 
                  "Cold War", "Distance", 
                  "time","time2","time3")
cf.names2.nc.p <- c("Intercept", "Donor Resource", 
                    "W == 0.25", "W == 0.50", "W == 0.75", "W == 1", 
                    "Recipient Wealth", "Recipient Wealth^2",
                    "Recipient Population", "Recipient Population^2", 
                    "Recipient Government Share", "Recipient Government Share^2", 
                    "Cold War", "Distance", 
                    "time","time2","time3", "Colony")

m2.0 <- createTexreg(coef.names = cf.names2, 
                     coef = summary(full2.0 $ Sol)[[1]][,1], 
                     se = summary(full2.0 $ Sol)[[1]][,2], 
                     ci.low = summary(full2.0 $ Sol)[[2]][,1],
                     ci.up = summary(full2.0 $ Sol)[[2]][,5])
m2.1 <- createTexreg(coef.names = cf.names2, 
                     coef = summary(full2.1 $ Sol)[[1]][,1], 
                     se = summary(full2.1 $ Sol)[[1]][,2], 
                     ci.low = summary(full2.1 $ Sol)[[2]][,1],
                     ci.up = summary(full2.1 $ Sol)[[2]][,5])
m2.p <- createTexreg(coef.names = cf.names2.p, 
                     coef = summary(full2.p $ Sol)[[1]][,1], 
                     se = summary(full2.p $ Sol)[[1]][,2], 
                     ci.low = summary(full2.p $ Sol)[[2]][,1],
                     ci.up = summary(full2.p $ Sol)[[2]][,5])

m2.nc0 <- createTexreg(coef.names = cf.names2.nc, 
                       coef = summary(spec2.0 $ Sol)[[1]][,1], 
                       se = summary(spec2.0 $ Sol)[[1]][,2], 
                       ci.low = summary(spec2.0 $ Sol)[[2]][,1],
                       ci.up = summary(spec2.0 $ Sol)[[2]][,5])
m2.nc1 <- createTexreg(coef.names = cf.names2.nc, 
                       coef = summary(spec2.1 $ Sol)[[1]][,1], 
                       se = summary(spec2.1 $ Sol)[[1]][,2], 
                       ci.low = summary(spec2.1 $ Sol)[[2]][,1],
                       ci.up = summary(spec2.1 $ Sol)[[2]][,5])
m2.ncp <- createTexreg(coef.names = cf.names2.nc.p, 
                       coef = summary(spec2.p $ Sol)[[1]][,1], 
                       se = summary(spec2.p $ Sol)[[1]][,2], 
                       ci.low = summary(spec2.p $ Sol)[[2]][,1],
                       ci.up = summary(spec2.p $ Sol)[[2]][,5])

## Table A.3
texreg(list(m2.ncp, m2.nc1, m2.nc0, m2.p, m2.1, m2.0), 
       custom.model.names = c("Pooled", "Colonial", "Non-colonial", "Pooled", 
                              "Colonial", "Non-colonial"),
       caption = "Bayesian Mixed-Effects Tobit Models of Bilateral Foreign Aid",
       reorder.coef = c(18, 2:14, 19:22, 15:17, 1))

sink(file = "output/tables/tableA3.txt")
print("Table A.3: Bayesian Mixed-Effects Tobit Models of Bilateral Foreign Aid (Alternative Specification)")
print(screenreg(list(m2.ncp, m2.nc1, m2.nc0, m2.p, m2.1, m2.0), 
          custom.model.names = c("Pooled", "Colonial", "Non-colonial", "Pooled", 
                                 "Colonial", "Non-colonial"),
          reorder.coef = c(18, 2:14, 19:22, 15:17, 1)))
sink()

# End of file